package com.example.utils;

import java.security.KeyFactory;
import java.security.PublicKey;
import java.security.spec.X509EncodedKeySpec;

import javax.crypto.Cipher;

import org.apache.commons.codec.binary.Base64;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class EncodeUtils {
	
	/**
	 * base64加密
	 * @param str
	 * @return
	 */
	public static String base64Encode(String str) {
		return Base64.encodeBase64String(str.getBytes());
	}
	/**
	 * base64解密
	 * @param str
	 * @return
	 */
	public static String base64Deccode(String str) {
		byte[] bytes = Base64.decodeBase64(str);
		return new String(bytes);
	}
	
	/**
     * 公钥加密
     * @param publicKeyText 公钥
     * @param text 要加密内容
     * @return 
     */
    public static String encryptByPublicKey(String publicKeyText, String pwd) {
        X509EncodedKeySpec x509EncodedKeySpec2 = new X509EncodedKeySpec(Base64.decodeBase64(publicKeyText));
        KeyFactory keyFactory;
        PublicKey publicKey;
        Cipher cipher;
        byte[] result;
        String retStr = "";
		try {
			keyFactory = KeyFactory.getInstance("RSA");
			publicKey = keyFactory.generatePublic(x509EncodedKeySpec2);
			cipher = Cipher.getInstance("RSA");
			cipher.init(Cipher.ENCRYPT_MODE, publicKey);
			result = cipher.doFinal(pwd.getBytes());
			retStr = Base64.encodeBase64String(result);
		} catch (Exception e) {
			log.error("RSA公钥加密异常：{}",e.getMessage());
			e.printStackTrace();
		}
        return retStr;
    }
}
